//
//  PersonInfoViewController.m
//  penzer
//
//  Created by caiyc on 2018/10/4.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "PersonInfoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AblityViewController.h"
@interface PersonInfoViewController ()<UIPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate,UITextViewDelegate>
@property(nonatomic,strong)UIImagePickerController *imagePicke;
@property(nonatomic,strong)UIImage *icons;
@property(assign)NSInteger sex;

@end

@implementation PersonInfoViewController
//保存
- (IBAction)savaInfo:(Regular_Btn *)sender {
    [self.view endEditing:1];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", nil]];
    NSDictionary *paramter = @{@"c":@"entry",@"i":@"10",@"ac":@"member",@"ctrl":@"live_anchor",@"token":[XTool GetDefaultInfo:HOST_USER][@"token"],@"op":@"member",@"m":@"bz_activities",@"ta":@"anchor_edit",@"sex":[NSString stringWithFormat:@"%ld",(long)self.sex],@"description":self.desc_Tv.text,@"age":self.age_Tf.text,@"shenjia":self.price_Tf.text,@"nickname":self.nick_Tf.text};
    
    NSLog(@"发布参数：%@",paramter);
    
    [manager POST:BASE_URL parameters:paramter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //        for(NSInteger i = 0; i < self.image_Array.count; i++) {
        if(self.icons){
            NSData * imageData = UIImageJPEGRepresentation(self.icons, 0.5);
            // 上传的参数名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
            //}
        }
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"上传回调===%@",responseObject);
        
        if([[responseObject objectForKey:@"message"][@"resultCode"]integerValue]==0)
        {
            [WToast showWithText:@"修改成功"];
            
            [self loadinfo];
        }
        else{
            [WToast showWithText:responseObject[@"message"][@"resultMessage"]];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WToast showWithText:@"更改失败请重试"];
        //  NSLog(@"上传失败原因===%@",error);
    }];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.icons = image;
    self.icon.image = image;
   // [self uploadImg];
    [self.imagePicke dismissViewControllerAnimated:YES completion:nil];
}
-(void)PickeImage{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            [WToast showWithText:@"相机功能受限，请检查"];
        }
        else
        {
            NSString * mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
            {
                [WToast showWithText:@"相机没权限，请在设置里面打开"];
                //没权限
                return ;
            }
            else if(!self.imagePicke)
            {
                self.imagePicke = [[UIImagePickerController alloc]init];
                self.imagePicke.sourceType = UIImagePickerControllerSourceTypeCamera;
                self.imagePicke.delegate = self;
                [self presentViewController:self.imagePicke animated:YES completion:nil];
            }
            else
            {
                self.imagePicke.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePicke animated:YES completion:nil];
            }
        }
        
        
    }];
    UIAlertAction *libra = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
        {
            [WToast showWithText:@"相机没权限，请在设置里面打开"];
            return ;
        }
        
        
        if(self.imagePicke)
        {
            self.imagePicke.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        else
        {
            self.imagePicke = [[UIImagePickerController alloc]init];
            self.imagePicke.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            self.imagePicke.delegate = self;
        }
        [self presentViewController:self.imagePicke animated:YES completion:nil];
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [self presentViewController:alert animated:YES completion:nil];
    [alert addAction:camera];
    [alert addAction:libra];
    [alert addAction:cancel];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigation:1 andTitle:@"个人资料" andNaviColor:[UIColor whiteColor] andTitleColor:nil];
    self.icon.userInteractionEnabled = 1;
    self.icon.layer.cornerRadius=45;
    self.icon.layer.masksToBounds = 1;
    self.desc_Tv.delegate = self;
    NSDictionary *userDic = [XTool GetDefaultInfo:HOST_USER];
    NSString *nickString = userDic[@"nickname"];
    self.nick_name.text = userDic[@"nickname"];
    self.nick_Tf.text = userDic[@"nickname"];
    self.age_Tf.text = [NSString stringWithFormat:@"%@",userDic[@"age"]];
    
    self.price_Tf.text =  [NSString stringWithFormat:@"%@",userDic[@"shenjia"]];
    //avatar
    NSURL *url = [NSURL URLWithString:userDic[@"avatar"]];
    [self.icon sd_setImageWithURL:url];
    NSInteger sex = [userDic[@"sex"]integerValue];
    self.sex = sex;
    if(sex==1){
        self.man_Btn.selected = 1;
    }else{
        self.woman_Btn.selected = 1;
    }
    self.mutable_Lab.hidden = 1;
    self.desc_Tv.text = userDic[@"description"];
   // self.age_Tf.text = userDic[@""]
    
    self.botom_ScroView.contentSize = CGSizeMake(screen_width, screen_height*1.3);
    self.botom_ScroView.delegate = self;
    self.botom_ScroView.showsVerticalScrollIndicator = 0;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(PickeImage)];
    [self.icon addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tapView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKb)];
    [self.view addGestureRecognizer:tapView];
    // Do any additional setup after loading the view from its nib.
}
-(void)loadinfo{
    NSDictionary *param = @{@"ta":@"get_member",@"op":@"member",@"ac":@"member",@"ctrl":@"live_anchor"};
    [self weqPostHandle:param success:^(id response) {
        if(response){
        NSDictionary *dic = [NSDictionary changeType:response[@"data"]];
        [XTool SaveDefaultInfo:dic Key:HOST_USER];
        [self.navigationController popViewControllerAnimated:NO];
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)hideKb{
     [self.view endEditing:1];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:1];
}
-(void)textViewDidChange:(UITextView *)textView{
    self.mutable_Lab.hidden = 1;
}
-(void)updateInfo{
    //更新个人信息

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)selectSex:(UIButton *)sender {
    sender.selected = !sender.selected;
    UIButton *man = (UIButton *)[self.view viewWithTag:1024];
    UIButton *woman = (UIButton *)[self.view viewWithTag:1025];
    if(sender.tag==1024){
        woman.selected = 0;
        self.sex = 1;
    }else{
        man.selected = 0;
        self.sex = 2;
    }
}
- (IBAction)selctBility:(UIButton *)sender {
    AblityViewController *bc= [[AblityViewController alloc]init];
    [self pushSecondVC:bc];
}
@end
